package com.lagou.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mcl
 * @date 2021/10/4 13:52
 * @description
 */
@Configuration
public class RabbitConfig {

    /**
     * 业务队列
     * @return
     */
    @Bean(name = "q.go")
    public Queue queue() {
        Map<String, Object> props = new HashMap<>();
        // 消息的生存时间 10s
        props.put("x-message-ttl", 10000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加 入死信队列）
        props.put("x-dead-letter-exchange", "ex.go.dlx");
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原 队列的routingKey
        props.put("x-dead-letter-routing-key", "go.dlx");
        Queue queue = new Queue("q.go", true, false, false, props);
        return queue;
    }

    /**
     * 死信队列
     * @return
     */
    @Bean(name = "q.go.dlx")
    public Queue queueDlx() {
        return new Queue("q.go.dlx", true, false, false);
    }

    /**
     * 业务交换器
     * @return
     */
    @Bean (name = "ex.go")
    public Exchange exchange() {
        return new DirectExchange("ex.go", true, false, null);
    }

    /**
     * 死信交换器
     * @return
     */
    @Bean (name = "ex.go.dlx")
    public Exchange exchangeDlx() {
        return new DirectExchange("ex.go.dlx", true, false, null);
    }

    @Bean
    public Binding binding(@Qualifier("q.go") Queue queue, @Qualifier("ex.go") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("go").noargs();
    }

    @Bean
    public Binding bindingDlx(@Qualifier("q.go.dlx") Queue queue, @Qualifier("ex.go.dlx") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("go.dlx").noargs();
    }
}
